using System;
using System.Collections.Generic;
using System.ComponentModel;

using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CodePlex.SpaceBlock;
using System.Threading;
using System.Diagnostics;
using CodePlex.Resourceful;

namespace CodePlex.SpaceBlock.UI.Controls.Explore
{
    public partial class FilesControl : CodePlex.SpaceBlock.UI.Controls.BaseControl, ISupportsFileSystem
    {
        public event EventHandler SelectedFilesChanged;
        public event EventHandler TransferToRequested;

        private IFileSystem _fileSystem;
        private Path _folder;
        private readonly DataGridView2 _grid;

       
        public FilesControl()
        {
            InitializeComponent();
           
            _grid = new DataGridView2();


            _grid.MouseDown += delegate(object sender, MouseEventArgs e)
            {
            
                // a click of any sort indicates "entering" this control
                this.OnEnter(EventArgs.Empty);
            };

           

            UIUtils.FillWith(_gridHolder, _grid);

            DataGridViewColumn col = _grid.AddColumnText("Name", 100);
            col.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

            DataGridViewColumn col2 = _grid.AddColumnText("Size", 80);
            col2.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            DataGridViewColumn col3 = _grid.AddColumnText("Last Modified", 100);
            col3.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            

            
            _grid.SortCompare += delegate(object sender, DataGridViewSortCompareEventArgs e)
            {
                if (e.Column == col2)
                {

                    long value1 = Utils.ParseSizeString(e.CellValue1 as string);
                    long value2 = Utils.ParseSizeString(e.CellValue2 as string);

                    e.SortResult = value1.CompareTo(value2);
                    e.Handled = true;
                }

                if (e.Column == col3)
                {

                    DateTime value1 = DateTime.Parse(e.CellValue1 as string);
                    DateTime value2 = DateTime.Parse(e.CellValue2 as string);

                    e.SortResult = value1.CompareTo(value2);
                    e.Handled = true;
                }
            };

       /*
            FormsUtils.ConfigureForDragDrop(_grid,delegate(Control control) {


                // folders
                TreeView treeview = control as TreeView;

                if (treeview != null)
                {
                    IFileSystemProvider fsProvider = treeview.Parent as IFileSystemProvider;

                    if (fsProvider != null)
                    {
                        return fsProvider.FileSystem != this.FileSystem;
                    }
                   
                }

             
                return true;
                
            },this.HandleDrop);
        */
            
            _grid.SelectionChanged += delegate
            {
                this.OnSelectedFilesChanged();
            };


            FilesControlModifiedContextMenu.Setup(_contextMenu, _grid);

        }



        public void Initialize(ActionManager manager, IFileSystem fileSystem) {

            _fileSystem = fileSystem;
            manager.AddAnchor(_grid);
        }

        public List<Path> SelectedFiles
        {
            get
            {
                return Utils.ToList(Utils.ConvertAll<DataGridViewRow, Path>(_grid.SelectedRows, delegate(DataGridViewRow row)
                {
                    return ((IFileItem)row.Tag).Path;
                }));
            }
        }

        public Path SelectedFolder
        {
            get
            {
                return _folder;
            }
            set
            {
                _folder = value;
                this.UpdateData();
            }
        }


        public IFileSystem FileSystem
        {
            get { return _fileSystem; }
        }


        private Path _pending;
        public void SelectFile(Path file)
        {
            this.InDisplay(delegate
            {
                foreach (DataGridViewRow r in _grid.Rows)
                {
                    IFileItem fi = r.Tag as IFileItem;
                    if (fi != null)
                    {
                        if (fi.Path.Equals(file))
                        {
                            _grid.ClearSelection();
                            r.Selected = true;
                            return;
                        }
                    }
                }
                _pending = file;



            });
        }







        private void OnSelectedFilesChanged()
        {
            if (this.SelectedFilesChanged != null)
            {
                this.SelectedFilesChanged(this, EventArgs.Empty);
            }
        }

        private void HandleDrop(Control sender, object[] dropValues)
        {
            if (_grid == sender)
            {
                return;
            }

            if (_folder == null)
            {
                return;
            }

            if (dropValues.Length > 0)
            {
                this.OnTransferToRequested();
                // this.UpdateData();
            }



        }

        private void UpdateData()
        {
            if (_folder == null)
            {
                return;
            }

            List<Path> oldSelection = new List<Path>(Utils.ConvertAll<DataGridViewRow, Path>(_grid.SelectedRows, delegate(DataGridViewRow item)
            {
                return ((IFileItem)item.Tag).Path;
            }));


            _grid.SuspendLayout();
            _grid.Rows.Clear();


            this.InBackground(delegate
            {

                IEnumerable<IFileItem> files = new List<IFileItem>();

                try
                {
                    files = _fileSystem.GetFiles(_folder);
                }
                catch (Exception ex)
                {
                    UIManager.Instance.ExceptionForm.Show(ex);
                }


                this.InDisplay(delegate
                {

                    bool firstMaintain = true;
                    bool tryPending = _pending != null;
                    foreach (IFileItem file in files)
                    {
                        DataGridViewRow r = _grid.AddRow(file,
                             UIManager.Instance.GetSmallImage(file.Path, false),
                             file.Path.Name,
                           Utils.ComputeSizeString(file.Size),
                           FilesControlModifiedContextMenu.FormatLastModified(file.LastModified)
                           );
                        if (tryPending && file.Path.Equals(_pending))
                        {
                            if (firstMaintain)
                            {
                                _grid.ClearSelection();
                                firstMaintain = false;
                            }
                            r.Selected = true;
                            _pending = null;

                        }
                        if (!tryPending && oldSelection.Contains(file.Path))
                        {
                            if (firstMaintain)
                            {
                                _grid.ClearSelection();
                                firstMaintain = false;
                            }
                            r.Selected = true;
                        }
                    }

                    _grid.ResumeLayout();

                    this.OnSelectedFilesChanged();

                   
                });
            });

        }

        private void OnTransferToRequested()
        {
            if (this.TransferToRequested != null)
            {
                this.TransferToRequested(this, EventArgs.Empty);
            }
        }



     
    }
}

